package com.littlebee.storysuper.utils;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 调用方式
 * @param <T>
 */
public abstract class CommonAdapter<T> extends BaseAdapter {
    protected final Context context;
    protected int layoutResId;
    protected final List<T> data;

    public CommonAdapter(Context context, int layoutResId) {
        this(context, layoutResId, (List)null);
    }

    public CommonAdapter(Context context, int layoutResId, List<T> data) {
        this.data = data == null?new ArrayList():new ArrayList(data);
        this.context = context;
        this.layoutResId = layoutResId;
    }

    public int getCount() {
        return this.data.size();
    }

    public T getItem(int position) {
        return position >= this.data.size()?null:this.data.get(position);
    }

    public long getItemId(int position) {
        return (long)position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = this.getAdapterHelper(position, convertView, parent);
        this.convert(viewHolder, this.getItem(position), position);
        return viewHolder.getView();
    }

    public void add(T elem) {
        this.data.add(elem);
        this.notifyDataSetChanged();
    }

    public void addAll(List<T> elem) {
        this.data.addAll(elem);
        this.notifyDataSetChanged();
    }

    public void set(T oldElem, T newElem) {
        this.set(this.data.indexOf(oldElem), newElem);
    }

    public void set(int index, T elem) {
        this.data.set(index, elem);
        this.notifyDataSetChanged();
    }

    public void remove(T elem) {
        this.data.remove(elem);
        this.notifyDataSetChanged();
    }

    public void remove(int index) {
        this.data.remove(index);
        this.notifyDataSetChanged();
    }

    public void replaceAll(List<T> elem) {
        this.data.clear();
        this.data.addAll(elem);
        this.notifyDataSetChanged();
    }

    public boolean contains(T elem) {
        return this.data.contains(elem);
    }

    public void clear() {
        this.data.clear();
        this.notifyDataSetChanged();
    }

    public List<T> getData() {
        return this.data;
    }

    protected abstract void convert(ViewHolder var1, T var2, int var3);

    protected ViewHolder getAdapterHelper(int position, View convertView, ViewGroup parent) {
        return ViewHolder.get(this.context, convertView, parent, this.layoutResId, position);
    }
}